/* eslint-disable standard/computed-property-even-spacing */
/* eslint-disable camelcase */
export function timeFix () {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome () {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent () {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function handleScrollHeader (callback) {
  let timer = 0

  let beforeScrollTop = window.pageYOffset
  callback = callback || function () {}
  window.addEventListener(
    'scroll',
    event => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        let direction = 'up'
        const afterScrollTop = window.pageYOffset
        const delta = afterScrollTop - beforeScrollTop
        if (delta === 0) {
          return false
        }
        direction = delta > 0 ? 'down' : 'up'
        callback(direction)
        beforeScrollTop = afterScrollTop
      }, 50)
    },
    false
  )
}

export function isIE () {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate (id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}
export function scorePassword (pass) {
  let score = 0
  if (!pass) {
    return score
  }
  // award every unique letter until 5 repetitions
  const letters = {}
  for (let i = 0; i < pass.length; i++) {
      letters[pass[i]] = (letters[pass[i]] || 0) + 1
      score += 5.0 / letters[pass[i]]
  }

  // bonus points for mixing it up
  const variations = {
      digits: /\d/.test(pass),
      lower: /[a-z]/.test(pass),
      upper: /[A-Z]/.test(pass),
      nonWords: /\W/.test(pass)
  }

  let variationCount = 0
  for (var check in variations) {
      variationCount += (variations[check] === true) ? 1 : 0
  }
  score += (variationCount - 1) * 10

  return parseInt(score)
}

/**
 * 生成图形验证码
 * @param String target canvas id
 * @param String keys 给定的随机字符串
 */
export function makeCode (options, callback) {
  if (options.target === undefined || options.target === null) return
  callback = callback || function () {}
  let verifyCode = ''
  setTimeout(() => {
    // 随机数
    const rn = (min, max) => {
      return parseInt(Math.random() * (max - min) + min)
    }
    // 随机颜色
    const rc = (min, max) => {
      var r = rn(min, max)
      var g = rn(min, max)
      var b = rn(min, max)
      return `rgb(${r},${g},${b})`
    }
    // 3.填充背景颜色,颜色要浅一点
    const w = 200
    const h = 40
    const ctx = document.querySelector(options.target).getContext('2d')
    ctx.fillStyle = rc(180, 230)
    ctx.fillRect(0, 0, w, h)
    // 4.随机产生字符串
    var pool = options.keys || 'abcdefghijklmnpqrstuvwxyz23456789'
    for (let i = 0; i < 4; i++) {
      var c = pool[rn(0, pool.length)] // 随机的字
      const tempStr = c.concat()
      verifyCode += tempStr.toString()
      var fs = rn(18, 40) // 字体的大小
      var deg = rn(-30, 30) // 字体的旋转角度
      ctx.font = fs + 'px Simhei'
      ctx.textBaseline = 'top'
      ctx.fillStyle = rc(80, 150)
      ctx.save()
      ctx.translate(30 * i + 15, 15)
      ctx.rotate(deg * Math.PI / 180)
      ctx.fillText(c, -15 + 5, -15)
      ctx.restore()
    }
    // 5.随机产生5条干扰线,干扰线的颜色要浅一点
    for (let i = 0; i < 5; i++) {
      ctx.beginPath()
      ctx.moveTo(rn(0, w), rn(0, h))
      ctx.lineTo(rn(0, w), rn(0, h))
      ctx.strokeStyle = rc(180, 230)
      ctx.closePath()
      ctx.stroke()
    }
    // 6.随机产生40个干扰的小点
    for (let i = 0; i < 40; i++) {
      ctx.beginPath()
      ctx.arc(rn(0, w), rn(0, h), 1, 0, 2 * Math.PI)
      ctx.closePath()
      ctx.fillStyle = rc(150, 200)
      ctx.fill()
    }
    callback(verifyCode)
  }, 100)
}

export function formateDropwn (dropdown, attrs = {}) {
  if (!Array.isArray(dropdown) || !dropdown.length) return []
  const title = attrs.title || 'DropValue'
  const value = attrs.value || 'DropID'
  const key = attrs.key || 'DropKey'
  const result = dropdown && dropdown.map(item => {
    item = {
      key: String(item[key]),
      title: item[title],
      value: String(item[value])
    }
    return item
  })
  return result
}

// 树形数据转扁平化
export function formateTreeData (treeList) {
  const result = []
  treeList && treeList.map(item => {
    if (item.children && item.children.length > 0) {
      result.push(...formateTreeData(item.children))
    }
    result.push(item)
  })
  return result
}

/** 判断是否为空
 * @description:
 * @param {*} value
 * @return {(Boolean)}
 */
 export const isEmpty = (value) => {
  switch (typeof value) {
    case 'undefined':
      return true
    case 'string':
      if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length === 0) return true
      break
    case 'boolean':
      if (!value) return true
      break
    case 'number':
      if (value === 0 || isNaN(value)) return true
      break
    case 'object':
      if (value === null || value.length === 0) return true
      // eslint-disable-next-line no-unreachable-loop
      for (const i in value) {
        return false
      }
      return true
  }
  return false
}

/**
 * @param {Number} len uuid的长度
 * @param {Boolean} firstU 将返回的首字母置为"u"
 * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
 */
 export function guid (len = 32, firstU = true, radix = null) {
	const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
	const uuid = []
	radix = radix || chars.length

	if (len) {
		// 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
		for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
	} else {
		let r
		// rfc4122标准要求返回的uuid中,某些位为固定的字符
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
		uuid[14] = '4'

		for (let i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | Math.random() * 16
				uuid[i] = chars[(i === 19) ? (r & 0x3) | 0x8 : r]
			}
		}
	}
	// 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
	if (firstU) {
		uuid.shift()
		return `u${uuid.join('')}`
	}
	return uuid.join('')
}
